package com.zhugang.week14.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @program algorithms
 * @description: CountDownLatcherTest
 * @author: chanzhugang
 * @create: 2022/09/16 10:43
 */
public class CountDownLatcherTest {

    class RPC implements Runnable {
        String url;
        CountDownLatch latch;

        // 一般都是通过构造函数传
        public RPC(String url, CountDownLatch latch) {
            this.url = url;
            this.latch = latch;
        }

        @Override
        public void run() {
            System.out.println("request");
            latch.countDown();
        }
    }

    /**
     * 主线程
     */
    public void run() throws InterruptedException {
        List<RPC> requests = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(4);
        requests.add(new RPC("rpc://A", latch));
        requests.add(new RPC("rpc://B", latch));
        requests.add(new RPC("rpc://C", latch));
        requests.add(new RPC("rpc://D", latch));
        // 开启4个线程
        requests.forEach((x) -> new Thread(x).start());
        latch.await();
        // merge 4 request result
        System.out.println("merge");

    }

    public static void main(String[] argv) throws InterruptedException {
        CountDownLatcherTest test = new CountDownLatcherTest();
        test.run();
    }
}